from flask import jsonify, request
from flask.views import MethodView
from app.extensions import db
from app.dbmodel import CommandRecord, DevLoginInfo
from app.utils.tool_openssh import SshToClient
import json



#
#        发送命令
#
#                 GET    /api/command/<int:command_id>     deviceInfo_id不能为0
#                 GET    /api/command/
# 向所有设备发送命令POST   /api/command/all
# 向选择设备发送命令POST   /api/command/
#                 DELETE     /api/command/<int:command_id>
class CommandAPI(MethodView):

    __methods__ = ["GET", "POST", "DELETE", "PUT", "PATCH"]

    def get(self, command_id):
        print('执行get')
        pass

    def post(self, command_id):
        print(f'执行POST: {command_id}')

        if command_id == None:
            print('执行指定设备ip的命令')
            clientData = request.get_json()
            print('clientData:',clientData)
            print('clientData类型:',type(clientData))
            commands = clientData.get('commands',None)
            commandNote = clientData.get('commandNote')
            deviceList = clientData.get('deviceList',None)
            recordSwitch = clientData.get('recordSwitch', 'off')
            result = []
            if not commands: return jsonify({'code': '1', 'msg': '未指定命令', "status": "1", "result": "failure"})
            if not deviceList: return jsonify({'code': '1', 'msg': '未指定设备', "status": "1", "result": "failure"})
            finalResult = []
            for deviceIp in deviceList:
                dev = DevLoginInfo.query.filter_by(DevIp=deviceIp).first()
                host = dev.DevIp
                port = dev.Port
                user = dev.User
                user_pwd = dev.UserPWD
                root_pwd = dev.RootPWD
                print(f'发起连接:{host}')
                print(f'执行命令:{commands},命令类型:{type(commands)}')
                client = SshToClient(host, port, user, user_pwd, root_pwd)
                try:
                    result = client.exec_command_root(commands)
                except TimeoutError:
                    print("连接超时...")
                print(host, port, user, user_pwd, root_pwd, commands, result)
                if recordSwitch == 'on':
                    command_record = CommandRecord(command=commands, note=commandNote, result=result)
                    db.session.add(command_record)
                    db.session.commit()
                print([dev.DevIp, dev.Port])
                finalResult.append((deviceIp, result))
            return jsonify({'code': '0', 'msg': 'success', "status": "success", "result": finalResult})

        if command_id == 'all':
            print('API: /api/command/all')
            command = request.form.get('command')
            commandNote = request.form.get('commandNote')
            switch = request.form.get('commandSwitch')
            result = None
            # count             = DevLoginInfo.query.count()
            # devLoginInfo_id   = 1
            print(command)
            devLoginInfo_list = DevLoginInfo.query.all()

            for dev in devLoginInfo_list:
                host = dev.DevIp
                port = dev.Port
                user = dev.User
                user_pwd = dev.UserPWD
                root_pwd = dev.RootPWD
                commands = [command, ]
                print(f'发起连接:{host}')
                client = SshToClient(host, port, user, user_pwd, root_pwd)
                try:
                    result = client.exec_command_root(commands)
                except TimeoutError:
                    print("连接超时...")
                    continue
                print(host, port, user, user_pwd, root_pwd, commands, result, command)
                if switch == 'on':
                    command_record = CommandRecord(
                        command=command, note=commandNote, result=result)
                    db.session.add(command_record)
                    db.session.commit()
            return jsonify({'code': '0', 'msg': 'success', "status": "0", "result": "success"})

        return jsonify({'code': '1', 'msg': 'error', "status": "1", "result": "error"})

    def delete(self, command_id):
        pass
